package com.martin.lib_base.model

import android.app.Activity
import android.content.Context
import com.martin.lib_base.bean.common.UploadBean
import com.martin.lib_base.interfaces.ILoading
import com.martin.lib_base.ktx.ResultBuilder
import com.martin.lib_base.ktx.getActivity
import com.martin.lib_base.ktx.handle
import com.martin.lib_base.ktx.launchCollect
import com.martin.lib_base.ktx.launchLoadingCollect
import com.martin.lib_base.ktx.showToast
import com.martin.lib_base.utils.MediaUtil
import com.martin.lib_base.utils.MediaUtilType
import com.martin.lib_base.utils.UploadUtil
import dev.utils.common.FileUtils
import kotlinx.coroutines.flow.MutableStateFlow

/**
 * @author：孟凡华
 * @date：2022/12/5
 * @desc：单张图片选择功能
 */
class SingleImagePickModel(
    //是否需要上传
    private val needUpload: Boolean = true,
    //加载框对象,用于展示上传时的等待框
    private val iLoading: ILoading? = null,
    private val maxSize: Int = 1024 * 1024 * 999,
    private val type: MediaUtilType = MediaUtilType.PICK_TAKE,
    /**
     * 成功回调
     * {needUpload}为false时,选择图片成功即调起
     * 为true时,上传图片成功才会调起
     */
    private val successCallBack: (SingleImagePickModel) -> Unit = {}
) {

    //图片本地地址
    val imagePath = MutableStateFlow("")

    //图片网络地址
    val imageUrl = MutableStateFlow("")

    var ossId = ""

    /**
     * 选择图片
     */
    fun picker(activity: Activity) {
        MediaUtil.pickImage(
            activity, 1,
            isCamera = type == MediaUtilType.PICK_TAKE
        ) {
            val realPath = it[0].realPath
            if (FileUtils.getFileLength(realPath) > maxSize) {
                showToast("图片过大,请重新选择")
                return@pickImage
            }
            if (needUpload) {
                uploadImage(realPath)
            } else {
                imagePath.value = realPath
                successCallBack(this@SingleImagePickModel)
            }
        }
    }

    fun picker(context: Context) {
        picker(context.getActivity())
    }

    /**
     * 上传图片
     */
    private fun uploadImage(path: String) {
        // 结果构建器
        val resultBuilder: ResultBuilder<UploadBean>.() -> Unit = {
            onSuccess = {
                imagePath.value = path
                imageUrl.value = it.data?.url ?: ""
                ossId = it.data?.ossId ?: ""
                successCallBack(this@SingleImagePickModel)
            }
        }
        // 判断是否有loading,有则使用loading,没有则使用普通的
        iLoading.handle({
            it.launchLoadingCollect({
                UploadUtil.upload(path)
            }, resultBuilder)
        }, {
            launchCollect({
                UploadUtil.upload(path)
            }, resultBuilder)
        })
    }
}